package warmachineroster.presentation.views;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.ViewPart;

import warmachinesystem.presentation.WarmachineSystemEditorPlugin;
import warmachinesystem.provider.WarmachineSystemItemProviderAdapterFactory;

public class WarmachineRosterListView extends ViewPart implements IResourceChangeListener{

	public static final String ID =
	      "warmachineroster.presentation.WarmachineRosterListViewID";
	private TreeViewer viewer;
	
	public WarmachineRosterListView() {
		 super();
		 ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
	}

	@Override
	public void dispose(){
		ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
	}

	@Override
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, 0);

		AdapterFactory gameSystemAdapterFactory = new WarmachineSystemItemProviderAdapterFactory();
		
		List <AdapterFactory> fList = new ArrayList<AdapterFactory>();
		fList.add(gameSystemAdapterFactory);
//		ComposedAdapterFactory composedFactory = new ComposedAdapterFactory(fList);
		
		
//		viewer.setContentProvider(new AdapterFactoryContentProvider(composedFactory));
		viewer.setContentProvider(new ITreeContentProvider() {
			
			@Override
			public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			}
			
			@Override
			public void dispose() {
			}
	

			@Override
			public Object[] getChildren(Object parentElement) {
				return null;
			}

			@Override
			public Object getParent(Object element) {
				return null;
			}

			@Override
			public boolean hasChildren(Object element) {
				return false;
			}

			@Override
			public Object[] getElements(Object inputElement) {
				System.out.println(inputElement.getClass());
				try {
					IProject project = (IProject) inputElement;
					project.refreshLocal(IProject.DEPTH_INFINITE, new NullProgressMonitor());
					IResource[] members  = project.members();
					List<IResource> result = new ArrayList<IResource>();
					for (IResource res : members){
						if(res.getFileExtension().equals("wmr")){
							result.add(res);
						}
					}
					return result.toArray();
				} catch (CoreException e) {
					throw new RuntimeException(e);
				}
			}
		});
//		viewer.setLabelProvider(new AdapterFactoryLabelProvider(composedFactory));
		viewer.setLabelProvider(new LabelProvider() {

			@Override
			public Image getImage(Object element) {
				return null;
			}

			@Override
			public String getText(Object element) {
				if (element instanceof IResource){
					IResource res = (IResource) element;
					return res.getName().substring(0,res.getName().lastIndexOf("."));
				}
				return super.getText(element);
			}});
		
        viewer.addSelectionChangedListener(new ISelectionChangedListener() {
            public void selectionChanged(SelectionChangedEvent event) {
            	System.out.println(event);
            }
        });
        
        viewer.addDoubleClickListener(new IDoubleClickListener() {
			
			@Override
			public void doubleClick(DoubleClickEvent event) {
				event.getSource();
				ISelection selection = event.getSelection();
				if (selection instanceof IStructuredSelection){
					IStructuredSelection ssel = (IStructuredSelection) selection;
					IFile res  = (IFile) ssel.getFirstElement();
					FileEditorInput fei = new FileEditorInput((IFile) res);
					try {
						getSite().getPage().openEditor(fei, PlatformUI.getWorkbench().
						        getEditorRegistry().getDefaultEditor(res.getName()).getId());
					} catch (PartInitException e) {
						throw new RuntimeException(e);
					}
				}
				
			}
		});
        
        IProject project = WarmachineSystemEditorPlugin.INSTANCE.getRootProject();
        
        viewer.setInput(project);
        

	}




	@Override
	public void setFocus() {
		viewer.getControl().setFocus();
	}


	@Override
	public void resourceChanged(IResourceChangeEvent event) {
		if (event.getType() == IResourceChangeEvent.POST_CHANGE){
			try {
				event.getDelta().accept(new IResourceDeltaVisitor() {
					
					@Override
					public boolean visit(IResourceDelta delta) throws CoreException {
						switch (delta.getKind()) {
						case IResourceDelta.ADDED:
						case IResourceDelta.REMOVED:
							viewer.refresh();
							break;

						default:
							break;
						}
						return true;
					}
				});
			} catch (CoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
